package com.hnjowe.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import org.apache.struts2.ServletActionContext;

import freemarker.template.*;

public class HtmlTemplateGenerator {

	private Configuration cfg = null;

	public HtmlTemplateGenerator() {
	} 
	
	public void init(String templatePath) {
		if (null == cfg) {
			cfg = new Configuration();
			cfg.setDefaultEncoding("UTF-8");
			cfg.setServletContextForTemplateLoading(ServletActionContext
					.getServletContext(), templatePath);
			cfg.setObjectWrapper(new DefaultObjectWrapper());
		}
	}
	
	/** 
     * 生成静态文件. 
     * @param templateFileName 	模板文件名及路径
     * @param propMap 			用于处理模板的属性Object映射 
     * @param htmlFilePath 		要生成的静态文件的路径 
     * @param htmlFileName 		要生成的静态文件的名称
     */ 
	public boolean createHtml(String ftlTemplate, 
						Map<String, Object> propMap,
						String htmlFilePath,
						String htmlFileName){
		
		boolean createResult = false;
		try {
			Template temp = cfg.getTemplate(ftlTemplate);
			String realPath = ServletActionContext.getServletContext().getRealPath(htmlFilePath);
			
			File file = new File(realPath);
			if (!file.exists())file.mkdirs();

			Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(realPath + "/" + htmlFileName), "UTF-8")); 
			
			temp.process(propMap, out);
			out.flush();
			out.close();
			createResult = true;
		} catch (TemplateException e) {
			createResult = false;
			System.out.println("HtmlTemplateGenerator createHtml():"+e);
		} catch (IOException e) {
			createResult = false;
			System.out.println("HtmlTemplateGenerator createHtml():"+e);
		}
		return createResult;
	}
}